package com.msi.shortwave;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.*;
import com.google.android.gms.maps.model.*;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TimePicker;
import android.widget.Toast;

public class maps extends Fragment implements  GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
	 View v;
	 
	 Location location = null;

	 static final LatLng HAMBURG = new LatLng(53.558, 9.927);
     static final LatLng KIEL = new LatLng(53.551, 9.993);
     private GoogleMap mapg;
     LocationClient lc;
     LocationRequest locationRequest;
 	ArrayList<Marker> markers = new ArrayList<Marker>();
 	
 	public Bitmap textAsBitmap(String text, float textSize, int textColor) {
 	    Paint paint = new Paint();
 	    paint.setTextSize(textSize);
 	    paint.setColor(textColor);
 	   
 	    paint.setTextAlign(Paint.Align.LEFT);
 	
 	    int width = (int) (paint.measureText(text) + 0.5f); // round
 	    float baseline = (int) (-paint.ascent() + 0.5f); // ascent() is negative
 	    int height = (int) (baseline + paint.descent() + 0.5f);
 	    Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
 	    Canvas canvas = new Canvas(image);
	
 	    canvas.drawText(text, 0, baseline, paint);
 	    return image;
 	}


public View onCreateView(LayoutInflater inflater, ViewGroup container,
                        Bundle savedInstanceState) {

   View v = inflater.inflate(R.layout.maps, null, false);

   locationRequest = LocationRequest.create();
   locationRequest.setFastestInterval(0);
   locationRequest.setNumUpdates(1);
   locationRequest.setInterval(0).setPriority(LocationRequest.PRIORITY_LOW_POWER);
   
   lc = new LocationClient(getActivity(), this, this);    
   lc.connect();
   
   mapg = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.mapgoogle))
           .getMap();
 
   
  /* mapg = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.mapgoogle))
       .getMap();
   
   */
 
   Bundle bund1 = getArguments();
   ArrayList<Bundle> trans = (ArrayList) bund1.getSerializable("markers");
   Boolean all = bund1.getBoolean("all");
   for(Bundle transitem : trans){
	
	   String longitude = transitem.getString("long");
		String latitude = transitem.getString("lat");
		String targetlat = transitem.getString("targetlat");
		String targetlong = transitem.getString("targetlong");
		String name = transitem.getString("name");
		String stationname = transitem.getString("stationname");

		String azi = transitem.getString("azi");
		
		String power = transitem.getString("power");
		Long type = transitem.getLong("type");
		String targets = transitem.getString("targets");
		String freq = transitem.getString("freq");
		
		if (type==1){
			//Log.i("SW3","hi" + type.toString());
			    Geocoder geocoder = new Geocoder(getActivity());
			    try {
			    	//Log.i("SW3",targets.trim());
			        List<Address> addresses = geocoder.getFromLocationName(targets.trim().toLowerCase(), 1);
			        if (addresses.size() > 0) {
			        	targetlat = String.valueOf(addresses.get(0).getLatitude());
			        	targetlong = String.valueOf(addresses.get(0).getLongitude());
			        	//Log.i("SW3","LAT" + targetlat);
			        	//Log.i("SW3","LONG" +targetlong);
			        }
			    } catch (IOException e) {
			        e.printStackTrace();
		        	
			    }
			}
		


		if (longitude.contains("W")){
			longitude=longitude.replace("W", ".");
			longitude = "-" + longitude;
		}else{
			longitude = longitude.replace("E", ".");
		}
		
		if (latitude.contains("S")){
			latitude = latitude.replace("S", ".");
			latitude = "-" + latitude;
		}else{
			latitude = latitude.replace("N", ".");
		}
	
		if (name.length() > 1){
		Marker kiel = mapg.addMarker(new MarkerOptions()
        .position(new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)))
        .title(name)
        .alpha(1).icon(BitmapDescriptorFactory.fromBitmap(textAsBitmap(name, 20, Color.BLACK))));
		markers.add(kiel);
		
		if (azi.length() > 1 && !azi.contains("ND") && !targetlat.equals("")){


			Location locationA = new Location("point A");

			locationA.setLatitude(Double.valueOf(latitude));
			locationA.setLongitude(Double.valueOf(longitude));

			Location locationB = new Location("point B");
			//Log.i("SW3",targetlat);
			locationB.setLatitude(Double.parseDouble(targetlat));
			locationB.setLongitude(Double.parseDouble(targetlong));

			float distance = locationA.distanceTo(locationB);
			
			
		
		
		double lat1 = Math.toRadians(Double.valueOf(latitude));
		double lon1 = Math.toRadians(Double.valueOf(longitude));
		if (power.length() < 1){
				power = "0";
		}
		
		if (power.contains(")")){
			power=power.replaceAll("[^0-9]", "");
		}
		
		if (Double.valueOf(freq.replace("Khz", "").trim()) < 2000){
			power = "0";
		}
		
		double d = (distance/1000)+((Double.valueOf(power)*10));
	
		
		
		Double brng = Math.toRadians(Double.valueOf(azi));
		Double lat2 = Math.asin( Math.sin(lat1)*Math.cos(d/6731) + 
		              Math.cos(lat1)*Math.sin(d/6731)*Math.cos(brng) );
		Double lon2 = lon1 + Math.atan2(Math.sin(brng)*Math.sin(d/6731)*Math.cos(lat1), 
		                     Math.cos(d/6731)-Math.sin(lat1)*Math.sin(lat2));
		Random randomGenerator = new Random();
		int randomInt = randomGenerator.nextInt(5);
		Marker target = mapg.addMarker(new MarkerOptions()
		
        .position(new LatLng(Math.toDegrees(lat2)+randomInt, Math.toDegrees(lon2)+randomInt))
        .alpha(1).icon(BitmapDescriptorFactory.fromBitmap(textAsBitmap(stationname + " - "+freq, 20, Color.BLUE))));
		
		double modilon1 =0;
		double modilon2= 0;
		double modilat1=0;
		double modilat2=0;;
	
		if (Double.valueOf(azi) > -1 & Double.valueOf(azi) < 46){
			modilon1 = 20;
			modilon2 = -20;
		}else if (Double.valueOf(azi) > 45 & Double.valueOf(azi) < 135){
			modilat1 = 20;
			modilat2 = -20;
		}else if (Double.valueOf(azi) > 134 & Double.valueOf(azi) < 225){
			modilon1 = 20;
			modilon2 = -20;
		}else if (Double.valueOf(azi) > 224 & Double.valueOf(azi) < 315 ){
			modilat1 = 20;
			modilat2 = -20;
		}else if (Double.valueOf(azi) > 314 & Double.valueOf(azi) < 361){
			modilon1 = 20;
			modilon2 = -20;
		}
		
		markers.add(target); 
		int colour = 0x3FFF0000;
		/*
		if (Double.valueOf(power) > -1 & Double.valueOf(power) < 101){
			colour = 0x3F66FF33;
		}else if (Double.valueOf(power) < 251 & Double.valueOf(power) > 101 ){
			colour = 0x3FFFFF00;
		}else if (Double.valueOf(power) < 501 & Double.valueOf(power) > 250 ){
			colour = 0x3FFF0000; }
		else{ 
			colour = 0x3FFF0000;
		}
		*/
			
		 PolygonOptions line=
			      new PolygonOptions().add(new LatLng(Double.parseDouble(latitude),
			    		  Double.parseDouble(longitude)),
			    		  new LatLng(Math.toDegrees(lat2)+modilat1, Math.toDegrees(lon2)+modilon1),
			    		  new LatLng(Math.toDegrees(lat2)+modilat2, Math.toDegrees(lon2)+modilon2))
			                           .fillColor(colour).strokeWidth(0).geodesic(true);

			  mapg.addPolygon(line);
		
			  
		}else{
			Random randomGenerator = new Random();

			if (azi.length() > 1 && azi.contains("ND")){
				  int randomInt = randomGenerator.nextInt(5);
				  int powermultiplier = 15000;
				  if (Double.valueOf(freq.replace("Khz", "").trim()) < 2000){
						powermultiplier = 1000;
					}
					int colour = 0x3FFF0000;


				Circle circle = mapg.addCircle(new CircleOptions()
			     .center(new LatLng(Double.parseDouble(latitude),
			    		  Double.parseDouble(longitude)))
			     .radius(Double.valueOf(power)*powermultiplier)
			    .strokeWidth(0)
			     .fillColor(colour));
				
				Marker target = mapg.addMarker(new MarkerOptions()
		        .position(new LatLng(Double.parseDouble(latitude)+randomInt, Double.parseDouble(longitude)))
		        .alpha(1).icon(BitmapDescriptorFactory.fromBitmap(textAsBitmap(stationname + " - "+freq, 20, Color.BLUE))));
				markers.add(target);
				
 			}else{
			
 				if (!targetlat.equals("")){
			  int randomInt = randomGenerator.nextInt(5);
			
			Marker target = mapg.addMarker(new MarkerOptions()
	        .position(new LatLng(Double.parseDouble(targetlat)+randomInt, Double.parseDouble(targetlong)))
	        .alpha(1).icon(BitmapDescriptorFactory.fromBitmap(textAsBitmap(stationname + " - "+freq, 20, Color.BLUE))));
			markers.add(target);
			
		
			
			 PolylineOptions line=
				      new PolylineOptions().add(new LatLng(Double.parseDouble(latitude),
				    		  Double.parseDouble(longitude)),
				                                
				                                new LatLng(Double.parseDouble(targetlat), Double.parseDouble(targetlong)))
				                           .width(5).color(Color.RED).geodesic(true);

				  mapg.addPolyline(line);
			//Log.i("SW3",targetlat + " " + targetlong);
 				}
 			}
		}
		
		}
		
					
		
	
	   
	 }
   
   



   return v;
}

public void onConnected(Bundle dataBundle) {
    // Display the connection status
    lc.requestLocationUpdates(locationRequest, this);
    location= lc.getLastLocation();
    if (location != null){
        

    }else{
    	LocationManager lm = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE); 
    	location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    }
    
    if (location != null){

	double longitude = location.getLongitude();
	double latitude = location.getLatitude();
    
    LatLng device = new LatLng(latitude,longitude);
    Marker deviceloc = mapg.addMarker(new MarkerOptions().position(device)
            .title("Your Location")
    .alpha(1).icon(BitmapDescriptorFactory.fromBitmap(textAsBitmap("Your Location", 20, Color.BLACK))));
    markers.add(deviceloc);
    
   

    // If already requested, start periodic updates
    }else{
    	
    	
    }
    LatLngBounds.Builder builder = new LatLngBounds.Builder();
  
	
	for (Marker marker : markers) {
        builder.include(marker.getPosition());
    }
    LatLngBounds bounds = builder.build();
    int padding = 100; // offset from edges of the map in pixels
    CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
    mapg.moveCamera(cu);
    mapg.animateCamera(cu);


}

@Override
public void onDisconnected() {
	// TODO Auto-generated method stub
	
}

@Override
public void onConnectionFailed(ConnectionResult result) {
	// TODO Auto-generated method stub
	
}

@Override
public void onLocationChanged(Location location) {
	// TODO Auto-generated method stub
	
}

public void onDestroyView() 
{
        super.onDestroyView(); 
        Fragment fragment = (getFragmentManager().findFragmentById(R.id.mapgoogle));  
        FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
        ft.remove(fragment);
        ft.commit();
}

}


